package service;

import com.dao.AccountDao;
import com.dao.AccountDaoImpl;
import exception.ActNoNotExistException;
import exception.MoneyNotEnoughException;
import exception.TransferException;
import pojo.Account;

import java.math.BigDecimal;

public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao = new AccountDaoImpl();

    @Override
    public void transfer(String fromActNo, String toActNo, BigDecimal money) throws MoneyNotEnoughException, ActNoNotExistException, TransferException {
        Account from = accountDao.selectAccountByActNo(fromActNo);
        if (from==null){
            throw new ActNoNotExistException("转账账户不存在");
        }

        BigDecimal fromMoney = from.getBalance().subtract(money);
        if (fromMoney.compareTo(new BigDecimal(0))<0){
            throw new MoneyNotEnoughException("余额不足");
        }

        Account to = accountDao.selectAccountByActNo(toActNo);
        if (to==null){
            throw new ActNoNotExistException("被转账账户不存在");
        }

        from.setBalance(fromMoney);
        BigDecimal toMoney = to.getBalance().add(money);
        to.setBalance(toMoney);
        accountDao.transfer(from,to);
    }
}
